package com.lm.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lm.service.UserService;
import com.lm.domain.User;

/**
 * UserController.
 * @author Leon Lee
 */
@RestController
@RequestMapping(value = "user")
public class UserController {

    /**
     * UserService interface.
     */
    @Autowired
    private UserService userService;

    /**
     * Get user MSG.
     * @param userId
     * @return user Msg
     */
    @RequestMapping(value = "/userMsg/{userId}", method = RequestMethod.GET)
    public User getUserMsg(@PathVariable(value = "userId") int userId) {
        return userService.getUserById(userId);
    }

    /**
     * Update user MSG.
     * @param userId
     * @param userName
     * @return updated user MSG
     */
    @RequestMapping(value = "userMsg/{userId}", method = RequestMethod.PUT)
    public User putUserMsg(@PathVariable(value = "userId") String userId, @RequestParam String userName, HttpSession session){
        if(null == session.getAttribute("loginUser")){
            return new User();
        }
        System.out.println((String)session.getAttribute("loginUser"));
        User user = new User(null, userName, "123", 12);
        userService.insert(user);
        return user;
    }

    /**
     * Delete user.
     * @param userId
     * @return deleted user MSG
     */
    @RequestMapping(value = "userMsg/{userId}", method = RequestMethod.DELETE)
    public int delUserMsg(@PathVariable(value = "userId") int userId){
        return userService.delete(userId);
    }

    /**
     * login User. Note that do not send password as url.
     * @param userId
     * @param password
     * @return
     */
    @RequestMapping(value = "userMsg/{userId}/{password}", method = RequestMethod.GET)
    public boolean loginUser(@PathVariable String userId, @PathVariable String password, HttpSession session){
        if("loginUser".equals(userId)&&"loginUser".equals(password)){
            session.setAttribute("loginUser", userId);
            return true;
        }
        return false;
    }
}
